import fs from 'fs';
import path from 'path';
import os from 'os';

export class SessionLog {
  constructor() {
    this.logDir = path.join(os.homedir(), '.sftp-cli', 'logs');
    this.ensureLogDir();
    this.sessionId = Date.now();
    this.sessionFile = path.join(this.logDir, `session_${this.sessionId}.log`);
    this.logs = [];
  }

  ensureLogDir() {
    if (!fs.existsSync(this.logDir)) {
      fs.mkdirSync(this.logDir, { recursive: true });
    }
  }

  log(type, message, metadata = {}) {
    const timestamp = new Date().toISOString();
    const logEntry = {
      timestamp,
      type,
      message,
      metadata,
    };

    this.logs.push(logEntry);

    // 同时写入文件
    try {
      fs.appendFileSync(
        this.sessionFile,
        JSON.stringify(logEntry) + '\n',
        'utf-8'
      );
    } catch (error) {
      console.error('写入日志文件失败:', error.message);
    }
  }

  logConnection(config) {
    this.log('CONNECTION', '建立连接', {
      host: config.host,
      port: config.port,
      username: config.username,
      authType: config.authType,
    });
  }

  logDisconnection() {
    this.log('DISCONNECTION', '断开连接');
  }

  logUpload(localPath, remotePath, size, duration) {
    this.log('UPLOAD', `上传文件`, {
      localPath,
      remotePath,
      size,
      duration,
    });
  }

  logDownload(remotePath, localPath, size, duration) {
    this.log('DOWNLOAD', `下载文件`, {
      remotePath,
      localPath,
      size,
      duration,
    });
  }

  logError(operation, error) {
    this.log('ERROR', `操作失败: ${operation}`, {
      error: error.message,
      code: error.code,
    });
  }

  getSessionFile() {
    return this.sessionFile;
  }

  getLogs() {
    return this.logs;
  }

  // 清理旧日志（超过 30 天）
  static cleanupOldLogs() {
    const logDir = path.join(os.homedir(), '.sftp-cli', 'logs');
    const maxAge = 30 * 24 * 60 * 60 * 1000; // 30 天

    if (!fs.existsSync(logDir)) return;

    try {
      const files = fs.readdirSync(logDir);
      files.forEach((file) => {
        const filePath = path.join(logDir, file);
        const stats = fs.statSync(filePath);
        const age = Date.now() - stats.mtimeMs;

        if (age > maxAge) {
          fs.unlinkSync(filePath);
        }
      });
    } catch (error) {
      console.error('清理日志文件失败:', error.message);
    }
  }
}
